package org.algorithm.wE1.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;

/**
 * @Date 2022/2/24
 * @Desc {https://leetcode-cn.com/problems/add-two-numbers/}
 */
public class 链表相加 {
    public static void main(String[] args) {
        int[] arr1 = {9,9,9,9,9};
        int[] arr2 = {9,9,9,9,9};
        ListNode l1 = ListNode.build(arr1);
        ListNode l2 = ListNode.build(arr2);
        System.out.println(ListNode.print(addTwoNumbers(l1,l2)));
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        ListNode sumNode = new ListNode(-1);
        ListNode pre = sumNode;
        //进位标志
        int j = 0;
        while (l1 != null || l2 != null || j!=0){
            int val1 = l1!=null?l1.val:0;
            int val2 = l2!=null?l2.val:0;
            int val3 = val1+val2+j;
            if(val3>9){
                pre.next = new ListNode(val3%10);
                j=1;
            }else{
                pre.next = new ListNode(val3);
                j=0;
            }
            pre = pre.next;
            l1 = l1!=null?l1.next:null;
            l2 = l2!=null?l2.next:null;
        }
        return  sumNode.next;
    }
}
